#include "_time.h"
#include "_time_struct_time.h"
#include "PikaVM.h"
#if defined(__linux)
#include <unistd.h>
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
#if defined(PIKA_FREERTOS_ENABLE)
#include "FreeRTOS.h"
#endif

pika_float utime_tick(PikaObj* self) {
    pika_float _tick =  (pika_float)__platform_getTick() / 1000;
    return _tick;
}

int utime_tick_ms(PikaObj* self) {
    return __platform_getTick();
}

void utime_sleep_until_ms(PikaObj* self, int last_ms_tick, int ms){
    #if defined(PIKA_FREERTOS_ENABLE)
    TickType_t xLastWakeTime = last_ms_tick;
    pika_GIL_EXIT();
    vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(ms));
    pika_GIL_ENTER();
    #endif
}

void utime_sleep_ms(PikaObj* self, int ms) {
    pika_GIL_EXIT();
    pika_sleep_ms(ms);
    pika_GIL_ENTER();
}

void utime_sleep(PikaObj* self, pika_float s){
    pika_GIL_EXIT();
    utime_sleep_ms(self, (int)(s * 1000));
    pika_GIL_ENTER();
}

void utime_sleep_until(PikaObj* self, pika_float last_tick, pika_float s){
    pika_GIL_EXIT();
    utime_sleep_until_ms(self,(int)(last_tick * 1000), (int)(s * 1000));
    pika_GIL_ENTER();
}
